<?php

# LemurCMS by Alec Gorge
#
#     This file contains the PHP functions used throught the CMS.
#
# updated: Jan. 12, 2009
# function delete_directory($dirname) {

class themeInstaller extends functions { 
	public function __construct ($file) {
		$this->path = BASE_URL."themes";
		$this->tempPath = BASE_URL."temp";
		$this->file = $file;
	}
	public function unlinkRecursive($dir, $deleteRootToo) {
		if(!$dh = @opendir($dir))
		{
			return;
		}
		while (false !== ($obj = readdir($dh)))
		{
			if($obj == '.' || $obj == '..')
			{
				continue;
			}

			if (!@unlink($dir . '/' . $obj))
			{
				$this->unlinkRecursive($dir.'/'.$obj, true);
			}
		}

		closedir($dh);
	   
		if ($deleteRootToo)
		{
			@rmdir($dir);
		}
	   
		return;
	}
	public function formatFileSize($fs) { 
		$bytes = array('KB', 'KB', 'MB', 'GB', 'TB'); 
		// values are always displayed in at least 1 kilobyte: 
		if ($fs <= 999) { 
			$fs = 1; 
		} 
		for ($i = 0; $fs > 999; $i++) { 
			$fs /= 1024; 
		} 
		return ceil($fs).$bytes[$i]; 
	}
	public function findexts () { 
		$filename = $this->file;
		$exts = explode(".", $filename);
		$n = count($exts)-1;
		$exts[$n] = ""; 
		$exts = implode($exts, ".");
		$exts = substr($exts, 0, -1);
		return rtrim($exts); 
	} 
	public function test ($file,$single) {
		$zip = new ZipArchive;
		if ($zip->open($file) === TRUE) {
			$zipx = $this->findexts();
			if(!is_dir($this->tempPath."/".$zipx)) {
				mkdir($this->tempPath."/".$zipx);
			}
		    $zip->extractTo($this->tempPath."/".$zipx.$name);
		    $zip->close();
			if(file_exists($this->tempPath.'/'.$single.'/index.tpl.php')) {
				$this->unlinkRecursive($this->tempPath."/".$zipx, true);
				//unlink($file);
				return 'true';
			}
			else {
				//$this->unlinkRecursive($this->tempPath."/".$zipx,true);
				return $this->message('error', 'Oh no! File missing!', 'There isn\'t a index.tpl.php file in the root the zip file. This is usally caused by having the theme folder inside the zip file.');
			}
		}
		else {
			echo $this->tempPath.'/'.$file;
		    return false;
		}
	}
	public function install ($file, $title) {
		$zip = new ZipArchive;
		if ($zip->open(BASE_URL.'temp/'.$file.'.zip') === TRUE) {
			if(!is_dir($this->path."/".$file)) {
				mkdir($this->path."/".$file);
			}
		    $zip->extractTo($this->path."/".$file.$name);
		    $zip->close();
			
			return true;
		}
		else {
		    return false;
		}
	}
}
?>
